<?php

class Zax_Module_User
{
	private $user;
	private $cookie;
	
	public function __construct()
	{
		if($_COOKIE['ZAX_COOKIE_V1'])
		{
			$this->cookie = unserialize($_COOKIE['ZAX_COOKIE_V1']);
			$this->authFromCookie();
		}
	}
	
	/**
	 * Essaie d'authentifier l'utilisateur d'après un couple 
	 * utilisateur/mot de passe
	 * Le mot de passe peut être un AuthID si $pass_is_AuthID est vrai
	 * 
	 * @param $username
	 * @param $password
	 * @param $pass_is_AuthID
	 * @return bool "true" si l'authentification réussit, "false" sinon
	 */
	public function auth($username,$password,$pass_is_AuthID = false)
	{
		global $Zax;
		
		if($pass_is_AuthID)
			$AuthID = $password;
		else
			$AuthID = sha1($username.md5($password));
		
		$User = $Zax->app->load("User");
		$User->File_Load("Users/$username.user");
		
		if($User->getAuthId() === $AuthID)
		{
			$this->user = $User;
			$this->cookie['username'] = $username;
			$this->cookie['AuthID'] = $AuthID;
			return true;
		}
		else
		{
			$Guest = $Zax->app->load("User");
			$Guest->File_Load("Users/Guest.user");
			$this->user = $User;
		}
	}
	
	/**
	 * Essaie d'authentifier l'utilisateur via son cookie
	 * @return bool "true" si l'authentification réussit, "false" sinon
	 */
	public function authFromCookie()
	{
		$username = $this->cookie['username'];
		$AuthID = $this->cookie['AuthID'];
		
		return $this->auth($username,$AuthID,true);
	}
	
	public function sendCookie()
	{
		setcookie('ZAX_COOKIE_V1',serialize($this->cookie),time()+99999999);
	}
}